// var baseUrl = "http://localhost:8989"
var baseUrl = "http://120.77.46.28:8989";
var userid = -1;

//angular js 相关代码
var app = angular.module('myApp', []);

app.controller('goodurl_controller', function ($http, $scope) {
    var vm = this;

    chrome.storage.sync.get({
        username: '未登录',
        password: ''
    }, function (items) {

        if (items.username == "未登录") {
            promptUser("未登录");
        } else {
            doLogin(items.username, items.password, vm, $scope);
        }
    });

    vm.addGoodUrl = function () {
        vm.goodurls.push({goodname: "", url: "", user_id: userid});
    };

    vm.storeGoodUrl = function () {
        //先处理一下数据 保证没有空的数据
        for (var i = vm.goodurls.length - 1; i >= 0; i--) {
            var goodurl = vm.goodurls[i];

            var goodname = goodurl['goodname'];
            var url = goodurl['url'];
            if (goodname == '' || goodname == undefined || url == '' || url == undefined) {
                vm.goodurls.splice(i, 1);
            }
        }
        if (vm.goodurls.length == 0) {
            alert('为空，请检查');
            return;
        }

        $http({
            url: baseUrl + '/option/store_good_url',
            method: 'POST',
            data: vm.goodurls
        }).then(function (result) {
            if (result.data.success == true) {
                alert("保存成功");
            } else {
                alert("保存失败，请联系客服");
            }
        });
    };
});

//航加入的，为了网页格式
window.onload = function () {
    var winHeight = document.documentElement.clientHeight;
    document.getElementById("win").style.height = winHeight + "px";
};

/**
 *注册按钮响应事件
 */
document.addEventListener('DOMContentLoaded', function () {
    //首先为两个按钮注册响应事件
    document.getElementById("bs_login_btn").addEventListener('click', login);
    document.getElementById("bs_register_btn").addEventListener('click', register);
    document.getElementById("btn_save_work_mode").addEventListener('click', saveBuyWorkMode);
    //检查是否已经登陆过了
});

/**
 *点击保存购买工作模式按钮
 */
function saveBuyWorkMode() {
    var mode = document.getElementsByClassName("input_work_mode")[0].value;
    if (mode == "1" || mode == 2) {
        chrome.storage.sync.set({
            buyWorkMode: mode
        }, function (items) {
            alert("存储模式成功\n现在的工作模式是 " + ((mode == 1) ? "直接购买商品" : "仅新增地址"));
        });

        chrome.runtime.sendMessage({
            type: "option_save_buy_work_mode",
            buyWorkMode: mode
        }, function (response) {
            console.log(response.farewell);
        });
    }
}


/**
 * 提示用户
 * @param str
 * @param flag
 */
function promptUser(str, flag) {
    document.getElementById("div_has_login").innerText = str;
}

/**
 * 从网页中拿到用户名和密码信息
 */
function register() {
    //从网页中读取用户名,密码
    var username = document.getElementsByName("username")[0].value;
    var password = document.getElementsByName("userpass")[0].value;

    if ((username == null) || (username == "")) {
        promptUser("请填写用户名");
        return;
    }
    if ((password == null) || (password == "")) {
        promptUser("请填写密码");
        return;
    }
    doRegister(username, password);
}

/**
 * 执行注册操作
 * @param username 用户名密码
 * @param password 密码
 */
function doRegister(username, password) {
    //构建get url
    var registerUrl = baseUrl
        + "/register"
        + "?username=" + username
        + "&password=" + password;

    console.log(registerUrl);
    //向服务器发送消息
    $.get(registerUrl, function (data, status) {
        //解析返回数据,
        //登录失败,服务器错误,提示用户原因
        if (status != "success") {
            promptUser("登录失败￣□￣｜｜\n请稍后再试");
        } else {
            //服务器没有错误,解析服务器返回值
            switch (data.code) {
                case "1000":
                    promptUser("此用户名已经被注册,请更换用户名");
                    break;
                case "1001":
                    //注册成功
                    //存储用户名密码
                    chrome.storage.sync.set({
                        username: username,
                        password: password
                    }, function (items) {
                        promptUser("已经成功注册,无需再次登录\n关闭此页面,直接使用即可");
                    });
                    //告诉background
                    chrome.runtime.sendMessage({
                        type: "option_login_success",
                        username: username,
                        password: password
                    }, function (response) {
                        console.log(response.farewell);
                    });
                    break;
            }
        }
    });
}

/**
 * 从网页中拿到用户名和密码
 */
function login() {
    //从网页中读取用户名,密码
    var username = document.getElementsByName("username")[0].value;
    var password = document.getElementsByName("userpass")[0].value;

    if ((username == null) || (username == "")) {
        promptUser("请填写用户名");
        return;
    }
    if ((password == null) || (password == "")) {
        promptUser("请填写密码");
        return;
    }

    doLogin(username, password);
}

/**
 * 登录
 * @param username 用户名
 * @param password 密码
 */
function doLogin(username, password, vm, scope) {
    //构建get url
    var loginUrl = baseUrl
        + "/login"
        + "?username=" + username
        + "&password=" + password;

    console.log(loginUrl);

    //向服务器发送消息
    $.get(loginUrl, function (data, status) {
        //解析返回数据,
        //登录失败,服务器错误,提示用户原因
        if (status != "success") {
            promptUser("登录失败￣□￣｜｜\n请稍后再试");
        } else {
            //服务器没有错误,检查用户名和密码是否匹配
            switch (data.code) {
                case "1":
                    promptUser("没有用户  " + username + "\n请重新登陆 或 注册");
                    break;
                case "2":
                    promptUser("密码错误");
                    break;
                case "3":
                    promptUser("账户 " + username + "   已经过期\n请及时充值 或 者更换账户登录");
                    break;
                case "4":
                    //成功登陆,没有过期
                    userid = data.data.id;
                    //存储用户名密码
                    chrome.storage.sync.set({
                            username: username,
                            password: password
                        }, function (items) {
                            //获取商品名和url
                            getGoodUrl(userid, vm, scope);
                            //提示用户
                            promptUser("已经成功登陆\n用户名 : " + username + "\t过期时间 : " + data.data.expirationTime + "\n如果最近清空过浏览器缓存，请使用脚本重启浏览器", true);
                            //告诉background
                            chrome.runtime.sendMessage({
                                type: "option_login_success",
                                username: username,
                                password: password
                            }, function (response) {
                                console.log(response.farewell);
                            });

                        }
                    );
                    break;
            }
        }
    });
}

function getGoodUrl(userid, vm, $scope) {
    //获取商品名和url
    var getGoodUrlUrl = baseUrl + '/option/get_good_url?userid=' + userid;
    $.get(getGoodUrlUrl, function (data, status) {
        //在option html页面上面显示
        $scope.$apply(function () {
            vm.goodurls = data.data;
        });

        //存储到本地，以便background js能够读到
        //存储用户名密码
        chrome.storage.sync.set({
                goodname_url: data.data
            }, function (items) {

            }
        )
        ;
    });
}
